package com.guosheng.service.impl;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.guosheng.dao.SysUserMapper;
import com.guosheng.pojo.ActiveUser;
import com.guosheng.pojo.SysUser;
import com.guosheng.pojo.SysUserExample;
import com.guosheng.service.SysUserService;
import com.guosheng.shiro.CustomRealm;
@Service
public class SysUserImpl implements SysUserService {

	@Autowired
	SysUserMapper sysUserMapper;
	
	@Autowired
	CustomRealm realm;
	
	@Override
	public List<SysUser> selectAllUser() {
		List<SysUser> list = sysUserMapper.selectAllUser();
		return list;
	}
	@Override
	public boolean insertUser(SysUser user) {
		//设置主键
			    String uuid=UUID.randomUUID().toString();
				user.setId(uuid.replaceAll("\\-", ""));
				 String salt=new Date().toString();
				 user.setSalt(salt);
		     Md5Hash md5Hash = new Md5Hash(user.getPassword(), salt, 1);
				String password_md5 =  md5Hash.toString();
				user.setPassword(password_md5);
		int i=sysUserMapper.insertUserRole(user);
		return i>0?true:false;
	}
	@Override
	public boolean deleteUser(String userId) {
		SysUserExample e=new SysUserExample();
		SysUserExample.Criteria criteria=e.createCriteria();
		criteria.andIdEqualTo(userId);
		return sysUserMapper.deleteByExample(e)>0?true:false;
	}
	@Override
	public SysUser selectByUserCode(String userCode) {
		SysUserExample e=new SysUserExample();
		SysUserExample.Criteria criteria=e.createCriteria();
		criteria.andUsercodeEqualTo(userCode);
		return sysUserMapper.selectByExample(e).get(0);
		
	}
	@Override
	public boolean updateUserPassword(String previousPassword,String passwordnew,SysUser activeUser) {
		SysUserExample e=new SysUserExample();
		SysUserExample.Criteria criteria=e.createCriteria();
		criteria.andUsercodeEqualTo(activeUser.getUsercode());
		SysUser sysuser=sysUserMapper.selectByExample(e).get(0);
	
			 String salt=sysuser.getSalt();
	        Md5Hash md5Hash = new Md5Hash(previousPassword, salt, 1);
			String previouspassword_md5 =  md5Hash.toString();
            if(previouspassword_md5.equals(sysuser.getPassword())){
            	 md5Hash = new Md5Hash(passwordnew, salt, 1);
     			String newpassword_md5 =  md5Hash.toString();
               sysuser.setPassword(newpassword_md5);
			return  sysUserMapper.updateByPrimaryKey(sysuser)>0?true:false;
			
		}
		return false;
	
}

}
